package com.tanhua.autoconfig.templates;

import com.baidu.aip.face.AipFace;
import com.tanhua.autoconfig.properties.AipFaceProperties;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;

public class AipFaceTemplate {

    @Autowired
    private AipFaceProperties properties;

    /**
     * 检测图片是否包含人脸
     *   返回值：boolean
     *   参数：检测的图片URL
     */
    public boolean detect(String imageUrl) {
        // 初始化一个AipFace
        AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");

        String imageType = "URL";

        // 人脸检测
        JSONObject res = client.detect(imageUrl, imageType, options);

        //res中包含一个error_code的属性，如果==0表示具有人脸
        return res.getInt("error_code") == 0;
    }
}
